/*eslint-env node*/

//------------------------------------------------------------------------------
// node.js starter application for Bluemix
//------------------------------------------------------------------------------

// my own modules
var sio=require('socket.io');
var moment=require('moment');

var mysql=require('mysql');

var http=require('http');
var names=[];



/*工具函数，应该封装成模块*/
var isNameAva=function(name){
	
	var answer=true;
	for (var i = 0; i < names.length; i++) {
		if(names[i]==name){
			answer=false;
			break;
		}
	};
		return answer;
};

function removeByValue(arr, val) {  
	 for(var i=0; i<arr.length; i++) { 
	 	if(arr[i] == val) { 
	 	      arr.splice(i, 1);     
	 	        break;   
	 	          } 
	 	            } 
	 	        } 

/******************************/

// This application uses express as its web server
// for more info, see: http://expressjs.com
var express = require('express');

// cfenv provides access to your Cloud Foundry environment
// for more info, see: https://www.npmjs.com/package/cfenv
var cfenv = require('cfenv');

// create a new express server
var app = new express();

var server=http.createServer(app);

// // serve the files out of ./public as our main files
// app.use(express.static(__dirname + '/public/broadcast.html'));


app.get('/',function(req,res){
 res.sendfile(__dirname+'/public/broadcast33.html');


})

/*这里不是很理解*/


var path=require('path');
app.use(express.static(path.join(__dirname,'public')));


// get the app environment from Cloud Foundry
var appEnv = cfenv.getAppEnv();

// start server on the specified port and binding host
server.listen(appEnv.port, '0.0.0.0', function() {

	// print a message when the server starts listening
  console.log("server starting on " + appEnv.url);

});



var bluemixClearDB={
        // jdbcUrl: "jdbc:mysql://us-cdbr-iron-east-03.cleardb.net/ad_14d1ffbbabc1749?user=bd4ddff12ce4d0&password=5a887197",
        // uri: "mysql://bd4ddff12ce4d0:5a887197@us-cdbr-iron-east-03.cleardb.net:3306/ad_14d1ffbbabc1749?reconnect=true",
        // name: "ad_14d1ffbbabc1749",
        host: "us-cdbr-iron-east-03.cleardb.net",
        port: "3306",
        user: "bd4ddff12ce4d0",
        password: "5a887197",
        database: "ad_14d1ffbbabc1749"
       
};

// if (process.env.VCAP_SERVICES) {
//     var env = JSON.parse(process.env.VCAP_SERVICES);
//     var credentials = env['mysql-5.5'][0].credentials;

//     var HOST = credentials.host;
//     var PORT = credentials.port;
//     var USER = credentials.user;
//     var PASSWORD = credentials.password;
//     var DATABASE = credentials.name;

// } else {
//     // Specify local Postgresql connection properties here.
//     var HOST = 'localhost';
//     var PORT = 3306;
//     var USER = 'Archer';
//     var PASSWORD = 'archer';
//     var DATABASE = 'bluemix';
// }
// var dbOptions={
// 	 host :'localhost',
//      port :3306,
//      user :'Archer',
//      password :'archer',
//      database :'bluemix'
//     };



	
var pool=mysql.createPool(bluemixClearDB);


var io=sio.listen(server);

io.sockets.on('connection',function(socket){
	console.log('建立scoket连接端口');
	

	

	socket.on('login',function(){
		socket.emit('login',names);	
	});
	

	socket.on('newUserLogin',function(name){
			if(isNameAva(name)){
			console.log('接收到新用户：'+name);
			names.push(name);
			console.log('所有用户有:'+names);
			//保存用户的昵称
			socket.myName=name;

			io.sockets.emit('login',names);
			io.sockets.emit('newUserLogin',name);
			socket.emit('loginConfirmed');
		 }else{
		 	socket.emit('repeatedName');
		 }

	});

	socket.on('chat',function(msg){
		



		pool.getConnection(function(err,connection){
			if(err){
				console.log('与数据库连接失败');
			}else{				
				/*插入记录sql语句(escape编码，防止sql注入)*/
				var insertSql="Insert into chatroom_records(username,record,_date) values("+connection.escape(socket.myName)+","+connection.escape(msg)+","+connection.escape( moment().format('YYYY-MM-DD HH:mm:ss'))+");";
				
				connection.query(insertSql,function(err,result){

					if(err){
							
						console.log('插入新纪录失败');
						console.log(err.code);
						connection.release();
					}
					else{
						console.log('聊天记录存储成功');
						connection.release();
					}
						
				});
			}


						

		});

		var currentTime=moment().format('YYYY-MM-DD HH:mm:ss');
		io.sockets.emit('chat',currentTime,msg,socket.myName);

	})



	socket.on('disconnect',function(){

		if(socket.myName&&socket.myName!=''){
		io.sockets.emit('disconnect',socket.myName);
		console.log(socket.myName+'已断开连接');
		removeByValue(names,socket.myName);
		socket.emit('login',names);
		socket.myName='';
		}	
	});


	socket.on('logout',function(){
		
		if(socket.myName&&socket.myName!=''){
		io.sockets.emit('disconnect',socket.myName);
		console.log(socket.myName+'已断开连接');
		removeByValue(names,socket.myName);
		socket.emit('login',names);
		socket.myName='';
		}	
	});


});


